import { _decorator, Collider2D, Component, Contact2DType, math, RigidBody2D, v3, Vec2, Vec3 } from 'cc';
import { Constant } from '../AshFramework/Datas/Constant';
import { Money } from './Money';
import { Monster } from './Monster';
import { Terminus } from './Terminus';
const { ccclass, property } = _decorator;

@ccclass('Arrow')
export class Arrow extends Component {
    private _rigidBoy: RigidBody2D = null;

    direction: Vec2 = new Vec2();
    rotate: number = 0;
    harm: number = 0
    private _speed: number = 30;
    private _dis = 1300;
    private _startPos: Vec3 = Vec3.ZERO;

    protected onLoad(): void {
        this._rigidBoy = this.getComponent(RigidBody2D);

        const collider2D: Collider2D = this.getComponent(Collider2D);
        if (collider2D) {
            collider2D.on(Contact2DType.BEGIN_CONTACT, this.beginContact, this);
        }
    }

    protected update(dt: number): void {

        if (this._rigidBoy) {
            this._rigidBoy.linearVelocity = this.direction.clone().multiplyScalar(this._speed);
        }

        if (this.node.position.clone().subtract(this._startPos).length() > this._dis) {
            this.node.destroy();
        }
    }

    fire(rotate: number, harm: number, startPos: Vec3) {
        this._startPos = startPos;
        this.rotate = rotate;
        this.harm = harm;
        this.node.setRotationFromEuler(v3(0, 0, this.rotate));
        this.getDir();
    }

    getDir() {
        this.rotate
        // 将角度转换为弧度
        let radians = math.toRadian(this.rotate);
        // 根据角度计算方向向量
        this.direction.x = Math.cos(radians);
        this.direction.y = Math.sin(radians);
    }

    beginContact(selfCollider: Collider2D, otherCollider: Collider2D) {

        if (otherCollider.group === Constant.Group.monster && otherCollider.tag == 0) {
            otherCollider.node.getComponent(Monster).beHit(this.harm);
            this.scheduleOnce(() => {
                this.node.destroy();
            })
        }
        if (otherCollider.group === Constant.Group.terminus && otherCollider.tag == 0) {
            otherCollider.node.getComponent(Terminus).beHit(this.harm);
            this.scheduleOnce(() => {
                this.node.destroy();
            })
        }
    }
}


